import time
from datetime import datetime
import logging
import evdev
from evdev import InputDevice, categorize, ecodes
import requests

# 设置日志
log_filename = f'/home/linaro/log/keyboard_log_{datetime.now().strftime("%Y%m%d")}.log'
logging.basicConfig(filename=log_filename,
                    level=logging.INFO,
                    format='%(asctime)s - %(message)s')

# 定义URLs
BASE_URL = 'http://dingtest.ddzn.tech:8000'
SHOPPING_URL = f'{BASE_URL}/shopping'  # 替换为实际的购物下单URL
OPERATOR_URL = f'{BASE_URL}/operator'  # 替换为实际的操作员补货URL

# 最后一次按键的时间戳
last_press_time = 0

def send_request(url):
    """向给定的URL发送POST请求"""
    try:
        response = requests.post(url)
        if response.status_code == 200:
            logging.info(f'Successfully sent request to {url}')
        else:
            logging.error(f'Failed to send request to {url}, status code: {response.status_code}')
    except Exception as e:
        logging.error(f'Error while sending request to {url}: {str(e)}')

def process_key_event(event):
    global last_press_time
    current_time = time.time()
    print("KeyEvent", current_time)

    if (current_time - last_press_time) > 10:
        if event.code == ecodes.KEY_DOWN and event.value == 1:
            logging.info('Up arrow pressed, sending shopping request.')
            send_request(SHOPPING_URL)
            last_press_time = current_time
        elif event.code == ecodes.KEY_UP  and event.value == 1:
            logging.info('Down arrow pressed, sending operator request.')
            send_request(OPERATOR_URL)
            last_press_time = current_time

def main():
    # 查找键盘设备
    devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
    # 监听键盘事件
    while True:
        try:
            keyboard_device = InputDevice('/dev/input/event3')
            logging.info(f"Listening on {keyboard_device.path} ({keyboard_device.name})")
            for event in keyboard_device.read_loop():
                if event.type == ecodes.EV_KEY:
                    process_key_event(event)
        except Exception as e:
            logging.warning(e)
            time.sleep(10)

if __name__ == "__main__":
    #send_request(OPERATOR_URL)
    main()
